package cn.fisok.pdman.dbconnector;

import cn.fisok.pdman.command.Command;
import cn.fisok.pdman.command.impl.*;
import cn.fisok.raw.kit.JSONKit;
import cn.fisok.raw.kit.StringKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 测试命令：
 */
public class Application {

    private static Logger logger = LoggerFactory.getLogger(Application.class);
    private static Map<String, Class<?>> commandRegister = new HashMap<String, Class<?>>() {{
        put("ping", PingDBCommand.class);
        put("dbReverseParse", DBReverseParseCommand.class);
        put("gendocx", GenDocxCommand.class);
    }};

    public static void main(String[] args) {

        //检查参数是不是没有
        if (args == null || args.length == 0) {
            String msg = "No Command Error.";
            System.err.println(msg);
            throw new RuntimeException(msg);
        }

        String cmdText = StringKit.nvl(args[0], "");

        List<String> argList = new ArrayList<String>();
        for (int i = 1; i < args.length; i++) {
            argList.add(args[i]);
        }

        Map<String, String> argMap = parseArgs(argList);

        //检查命令的合法性
        Class<?> cmdClass = commandRegister.get(cmdText);
        if (cmdClass == null) {
            String msg = "Command [" + cmdText + "] Not Supported.";
            System.err.println(msg);
            throw new RuntimeException(msg);
        }



        logger.info("========================================================================================");
        logger.info("执行命令:" + cmdText + " " + StringKit.join(argList, " "));
        logger.info("========================================================================================");

        try {
            String userHome = System.getProperties().getProperty("user.home");
            String filePath = userHome + File.separator +"logs"+File.separator+"pdman"+File.separator+"test.txt";
            File file = new File(filePath);
            if(!file.exists()) {
                file.createNewFile();
            }
            System.setErr(new PrintStream(new FileOutputStream(file)));
            Command<?> cmd = (Command<?>) cmdClass.newInstance();
            Object ret = cmd.exec(argMap);
            String retText = "";

            if (ret instanceof String) {
                retText = (String) ret;
            } else if (ret instanceof Number) {
                retText = ((Number) ret).toString();
            } else {
                retText = JSONKit.toJsonString(ret);
            }

            System.out.println(retText);
        } catch (InstantiationException e) {
            System.err.println(e);
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            System.err.println(e);
        } catch (Exception e) {
            logger.error("未知的错误", e);
            System.err.println(e);
            throw new RuntimeException(e);
        }
    }


    public static Map<String, String> parseArgs(List<String> argList) {

        Map argsMap = new HashMap();

        argList.forEach(x -> {
            x = x.replace("\"","").replace("\'","");
            int idx = x.indexOf("=");
            if (idx > 0) {
                String key = x.substring(0, idx);
                String value = x.substring(idx + 1);
                argsMap.put(key, value);
            }
        });

        return argsMap;
    }


}
